package com.newlink.building.common_base.widget.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.newlink.building.common_base.R

/**
 * @Author: Jake
 * @Date: 2023-03-29
 * @Description:
 */
@SuppressLint("InflateParams")
class SettingsItemView : RelativeLayout {


    private var mTitle: String? = null
    private var mSubTitle: String? = null
    private var mIcon: Drawable? = null


    private lateinit var titleView: TextView
    private lateinit var subTitleView: TextView
    private lateinit var iconView: ImageView

    var mSettingsItemClickLister: OnItemClickLister? = null

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        val view = inflate(context, R.layout.layout_settings_item, this)

        titleView = view.findViewById(R.id.settings_item_title)
        subTitleView = view.findViewById(R.id.settings_item_subtitle)
        iconView = view.findViewById(R.id.settings_item_icon)

        view.setOnClickListener {
            mSettingsItemClickLister?.onSettingsItemClick(it)
        }

        context.theme.obtainStyledAttributes(
            attrs,
            R.styleable.SettingsItem,
            0, 0
        ).apply {
            try {
                val drawable = getResourceId(R.styleable.SettingsItem_iconRes, 0)
                if (drawable != 0) {
                    setSettingsIcon(drawable)
                } else {
                    iconView.visibility = View.GONE
                }
                setSettingTitle(getString(R.styleable.SettingsItem_title))
                setSettingsSubTitle(getString(R.styleable.SettingsItem_subTitle))
            } finally {
                recycle()
            }
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    fun setSettingsIcon(drawableRes: Int) {
        if (drawableRes > 0) {
            iconView.setImageDrawable(context.resources.getDrawable(drawableRes, context.theme))
        } else {
            iconView.visibility = View.GONE
        }
    }

    fun setSettingTitle(title: String?) {
        title?.let {
            titleView.text = it
        }
    }

    fun setSettingsSubTitle(subTitle: String?) {
        subTitle?.let {
            subTitleView.text = it
            subTitleView.visibility = View.VISIBLE
        }
    }

    fun setOnSettingsItemClickListener(lister: OnItemClickLister) {
        this.mSettingsItemClickLister = lister
    }


    interface OnItemClickLister {
        fun onSettingsItemClick(v: View)
    }
}